policeinfo = {
  initcallinfoPage:function() {
    this.data = {
      pageNum: 0,
      queryData: {
        areaId: '',
        platformName: '',
        owersName: '',
        vehicleNo: '',
        transType: '',
        startTime: '',
        endTime: '',
        classify: '1',
        page: 1,
        size: 10
      },
      attr: [],
      systemPolice: [
        {
          field: 'no',
          title: '序号',
          align: 'center',
					formatter: function (value, row, index) {
            var pageSize = policeinfo.data.queryData.size;
            var pageNumber = policeinfo.data.queryData.page;
            return pageSize * (pageNumber - 1) + index + 1;
          }
        },
        {
            field: 'vehicleNo',
            title: '车牌号'
        },
        {
            field: 'areaName',
            title: '地区'
        },
        {
            field: 'platformName',
            title: '平台',
        },
        {
            field: 'owerName',
            title: '企业',
        },
        {
            field: 'vehicleType',
            title: '车辆类型',
        },
        {
            field: 'vehicleColor',
            title: '车牌颜色',
        },
        {
            field: 'transTypeName',
            title: '行业类型',
        },
        {
            field: 'allNum',
            title: '报警次数',
        },
        {
            field: 'disposeNum',
            title: '已处理',
        },
        {
            field: 'untreatedNum',
            title: '未处理',
        }
      ],
      accidentViolationPolice: [
        {
          field: 'no',
          title: '序号',
          align: 'center',
					formatter: function (value, row, index) {
            var pageSize = policeinfo.data.queryData.size;
            var pageNumber = policeinfo.data.queryData.page;
            return pageSize * (pageNumber - 1) + index + 1;
          }
        },
        {
            field: 'vehicleNo',
            title: '车牌号'
        },
        {
            field: 'areaName',
            title: '地区'
        },
        {
            field: 'platformName',
            title: '平台',
        },
        {
            field: 'owerName',
            title: '企业',
        },
        {
            field: 'vehicleType',
            title: '车辆类型',
        },
        {
            field: 'vehicleColor',
            title: '车牌颜色',
        },
        {
            field: 'transTypeName',
            title: '行业类型',
        },
        {
            field: 'alarmType',
            title: '报警类型',
        },
        {
            field: 'alarmTime',
            title: '报警时间',
        },
        {
            field: 'speed',
            title: '报警速度',
        },
        {
            field: 'result',
            title: '处理状态',
        },
      ],
      activeSafetyPolice: [
        {
          field: 'no',
          title: '序号',
          align: 'center',
          formatter: function (value, row, index) {
            var pageSize = policeinfo.data.queryData.size;
            var pageNumber = policeinfo.data.queryData.page;
            return pageSize * (pageNumber - 1) + index + 1;
          }
        },
        {
            field: 'vehicleNo',
            title: '车牌号'
        },
        {
            field: 'areaName',
            title: '地区'
        },
        {
            field: 'platformName',
            title: '平台',
        },
        {
            field: 'owerName',
            title: '企业',
        },
        {
            field: 'vehicleType',
            title: '车辆类型',
        },
        {
            field: 'vehicleColor',
            title: '车牌颜色',
        },
        {
            field: 'transTypeName',
            title: '行业类型',
        },
        {
            field: 'alarmType',
            title: '报警类型',
        },
        {
            field: 'alarmLevel',
            title: '报警等级',
        },
        {
            field: 'alarmTime',
            title: '报警时间',
        },
        {
            field: 'speed',
            title: '报警速度',
        },
        {
            field: 'result',
            title: '处理状态',
        }
      ],
      DATAPICKERAPI: {
        // 默认input显示当前月,自己获取后填充
        activeMonthRange: function () {
          return {
            begin: moment().set({ 'date': 1, 'hour': 0, 'minute': 0, 'second': 0 }).format('YYYY-MM-DD HH:mm:ss'),
            end: moment().set({ 'hour': 23, 'minute': 59, 'second': 59 }).format('YYYY-MM-DD HH:mm:ss')
          }
        },
        shortcutMonth: function () {
          // 当月
          var nowDay = moment().get('date');
          var prevMonthFirstDay = moment().subtract(1, 'months').set({ 'date': 1 });
          var prevMonthDay = moment().diff(prevMonthFirstDay, 'days');
          return {
            now: '-' + nowDay + ',0',
            prev: '-' + prevMonthDay + ',-' + nowDay
          }
        },
        // 近n小时计算返回
        shortcutPrevHours: function (hour) {
          var nowDay = moment().get('date');
          var prevHours = moment().subtract(hour, 'hours');
          var prevDate=prevHours.get('date')- nowDay;
          var nowTime=moment().format('HH:mm:ss');
          var prevTime = prevHours.format('HH:mm:ss');
          return {
            day: prevDate + ',0',
            time: prevTime+',' + nowTime,
            name: '近'+ hour+'小时'
          }
        },
        // 注意为函数：快捷选项option:只能同一个月份内的
        rangeMonthShortcutOption1: function () {
          var result = DATAPICKERAPI.shortcutMonth();
          // 近18小时
          var resultTime= DATAPICKERAPI.shortcutPrevHours(18);
          return [{
            name: '昨天',
            day: '-1,-1',
            time: '00:00:00,23:59:59'
          }, {
            name: '这一月',
            day: result.now,
            time: '00:00:00,'
          }, {
            name: '上一月',
            day: result.prev,
            time: '00:00:00,23:59:59'
          }, {
            name: resultTime.name,
            day: resultTime.day,
            time: resultTime.time
          }];
        },
        // 快捷选项option
        rangeShortcutOption1: [
          {
            name: '最近三天',
            day: '-2,0'
          }, {
            name: '最近一周',
            day: '-6,0'
          }, {
            name: '最近一个月',
            day: '-29,0'
          }, {
            name: '最近三个月',
            day: '-90, 0'
          }
        ],
        singleShortcutOptions1: [{
          name: '今天',
          day: '0',
          time: '00:00:00'
        }, {
          name: '昨天',
          day: '-1',
          time: '00:00:00'
        }, {
          name: '一周前',
          day: '-7'
        }]
      }
    },
    this.initTime();
    this.btnEvent();
    this.getSystemData(); // 表格初始化
    this.getChartsData(); // charts
    this.selectInputInit();
    this.selectedValue(); // select下拉
  },
  selectInputInit() { // 地区input级联选择
    jrequest.get("/api/assessMent/selectByArea",{}).then(res => {
      var data = res.data;
      data[0].code=1;
				$.each(data[0].cityAreaVOS,function(i,dom){
					data[0].cityAreaVOS[i].code=2;
					$.each(data[0].cityAreaVOS[i].cityAreaVOS,function(j,dom){
						data[0].cityAreaVOS[i].cityAreaVOS[j].code=3;
					})
				})
				this.creatMainRido("qrm-main",data,"cityAreaVOS","code");
    })
  },
  creatMainRido:function(id,attr,child,jibie){
		$(id).html("");
		var sttrdiv="";
		for(var i=0;i<3;i++){
			sttrdiv +="<div class='qrm-border"+(i+1)+"' style='display:none'>"+
				"<ul class='qrm-lev-"+(i+1)+" qrm-lev' id='qrm-border1'>"+
				"</ul>"+
				"</div>"
		};
		$(".qrm-main").html(sttrdiv);
		var str="";
		$("#qrm-border1").html("");
		var forTree = function(o){
			for(var i=0;i<o.length;i++){
				var urlstr = "";
				try{
					urlstr = "<li><span data-id='"+o[i]["id"]+"'>"+ o[i]["name"] +"</span><i class='qrm-arrow-right'></i><ul class='li-zi-"+o[i][jibie]+"' style='display: none'>";
					str += urlstr;
					if(o[i][child] != null){
						forTree(o[i][child]);
					}
					str += "</ul>";
				}catch(e){}
			}
			return str;
		};
		$("#qrm-border1").html(forTree(attr));
	},
  getQueryData() {
    this.data.queryData.areaId = $(".j-search-row .item").eq(0).find("input").attr("data-id") || "";
    this.data.queryData.platformName = $(".platformName input").val();
    this.data.queryData.owersName = $(".owersName input").val();
    this.data.queryData.vehicleNo = $(".vehicleNo input").val();
    this.data.queryData.transType = $(".acciden_industry_type .combo-select .combo-dropdown li.option-selected").index();
    this.data.queryData.startTime = $(".policeInfo_starttime").val();
    this.data.queryData.endTime = $(".policeInfo_endtime").val();
  },
  resetQueryData() {
    this.data.queryData.areaId = $(".j-search-row .item").eq(0).find("input").attr("data-id","");
    $(".qrm-input").val('');
    this.data.queryData.platformName = $(".platformName input").val('');
    this.data.queryData.owersName = $(".owersName input").val('');
    this.data.queryData.vehicleNo = $(".vehicleNo input").val('');
    $(".acciden_industry_type .combo-select .combo-dropdown li:first-child").addClass("option-selected").siblings().removeClass("option-selected"); // 行业类别
    $(".acciden_industry_type .combo-select .combo-input").val("全部");
    this.data.queryData.startTime = $(".policeInfo_starttime").val('');
    this.data.queryData.endTime = $(".policeInfo_endtime").val('');
    this.setDatepickerTime();
  },
  initBootTable(data,columns,total) {
    $('#cnf_reportTable').bootstrapTable({
      method: 'get',
      cache: false,
      height: 200,
      pagination: true,
      pageSize: policeinfo.data.queryData.size,
      pageNumber:policeinfo.data.queryData.page,
      pageList: [10, 25, 50, 100],
      showColumns: true,
      striped: true,
      columns: columns,
      data :data,
      sidePagination: 'server', // client or server
      totalRows: total,
      onPageChange: function (size, number) {
        policeinfo.data.queryData.size = size;
        policeinfo.data.queryData.page = number;
        policeinfo.queryTableData();
      },
      formatNoMatches: function(){
          return '暂无数据';
      }
    })
  },
  getSystemData() {
    this.data.queryData.classify = "1,2,3"
    this.getQueryData();
    jrequest.get("/api/alarm-infos/collect",this.data.queryData).then(res => {
      $("#cnf_reportTable").bootstrapTable('destroy');
      this.initBootTable(res.data,this.data.systemPolice,res.total);
    })
  },
  getAccidentData() {
    this.data.queryData.classify = '1';
    this.getQueryData();
    jrequest.get("/api/alarm-infos/classify",this.data.queryData).then(res => {
      $("#cnf_reportTable").bootstrapTable('destroy');
      this.initBootTable(res.data,this.data.accidentViolationPolice,res.total);
    })
  },
  getActiveSafetyData() {
    this.data.queryData.classify = '2';
    this.getQueryData();
    jrequest.get("/api/alarm-infos/classify",this.data.queryData).then(res => {
      $("#cnf_reportTable").bootstrapTable('destroy');
      this.initBootTable(res.data,this.data.activeSafetyPolice,res.total);
    })
  },
  getViolationData() {
    this.data.queryData.classify = '3';
    this.getQueryData();
    jrequest.get("/api/alarm-infos/classify",this.data.queryData).then(res => {
      $("#cnf_reportTable").bootstrapTable('destroy');
      this.initBootTable(res.data,this.data.accidentViolationPolice,res.total);
    })
  },
  getChartsData() { // 图标数据查询
    var chartsData = {};
    chartsData.startTime = $(".policeInfo_starttime").val() || "2019-08-09";
    chartsData.endTime = $(".policeInfo_endtime").val() || "2019-08-15";
    var chartsxAxis9 = []; // line时间
    var chartName9= ["非位置相关报警类型","主动安全报警类型","位置相关报警类型"];
    var pielenged=['已处理', '未处理'];
    var color9= [['#00FFf4','#00FFFF'],['#E1E02C','#DB5134'],['#028CFE','#267BCB']];
    var chartCount9 = [[],[],[]]; // line数据数组
    var roundDataycl=[[],[],[]];
    var roundwclcount=[[],[],[]];
    var havedata = 0; // 已处理数
    var notdata = 0; // 未处理数
    var totaldata = 0; // 总数
    var haveLv = 0;
    var notLv = 0;
    jrequest.get("/api/alarm-infos/echarts",chartsData).then(res => {
      console.log(res)
      res.data.forEach(item => {
        console.log(Math.floor(item.alarmActive)- Math.floor(item.alarmQualifiedAccident))
        chartsxAxis9.push(item.time);
        chartCount9[0].push(item.alarmAccident);
        chartCount9[1].push(item.alarmActive);
        chartCount9[2].push(item.alarmViolation);
        roundDataycl[0].push({
          name:chartName9[0],
          value:item.alarmQualifiedAccident
        });
        roundDataycl[1].push({
          name:chartName9[1],
          value:item.alarmQualifiedActive
        });
        roundDataycl[2].push({
          name:chartName9[2],
          value:item.alarmQualifiedViolation
        });
        roundwclcount[0].push({
          name:chartName9[0],
          value:Math.floor(item.alarmAccident) - Math.floor(item.alarmQualifiedAccident)
        })
        roundwclcount[1].push({
          name:chartName9[1],
          value:Math.floor(item.alarmActive) - Math.floor(item.alarmQualifiedActive)
        })
        roundwclcount[2].push({
          name:chartName9[2],
          value:Math.floor(item.alarmViolation) - Math.floor(item.alarmQualifiedViolation)
        })
      });

      console.log(roundwclcount)
      var chartName= ["非位置相关报警类型","位置相关报警类型"];
      var convertData = function(data,count) {
        var res = [];
        $.each(count,function(i){
          res[i]=[];
          $.each(count[i],function(j){
            for (var t= 0; t < data.length; t++){
               if(data[t]==count[i][j].name){
                 res[i].push({
                   name:data[t],
                   value:Math.floor(count[i][j].value)
                 })
               }

            }

          })
        });
        return res;
      };
      function creatAttr(chartName){
        var roundData = [];
        var totaldatalcl = 0; // 已处理数
        var totalwcls = 0; // 已处理数
        var hascount=convertData(chartName,roundDataycl);
        var nocount=convertData(chartName,roundwclcount);
        $.each(hascount,function(i){
          $.each(hascount[i],function(j){
            totaldatalcl+=Math.floor(hascount[i][j].value)
          })
        });
        $.each(nocount,function(i){
          $.each(nocount[i],function(j){
            totalwcls+=Math.floor(nocount[i][j].value)
          })
        });
        roundData.push({value: totaldatalcl,name: pielenged[0]});
        roundData.push({value: totalwcls,name: pielenged[1]});
        let pieCorlor = ["#fafd21",'#3e6afa'];
        var widthadd=$(window).width()*0.45-10;
        $("#pieCharts").css({width:widthadd,height:"320px"});
        charts.systemWarnPie("pieCharts",pielenged,roundData,"circle","#fff",pieCorlor);
      }
      creatAttr(chartName9);
      var widthadd=$(window).width()*0.45-10;
      $("#lineCharts").css({width:widthadd,height:"320px"});
      var  myChart = echarts.init(document.getElementById('lineCharts'));

      myChart.clear();
      myChart.setOption(charts.LinesArea(chartName9,chartsxAxis9,chartCount9,color9));

      myChart.on('legendselectchanged', function(obj) {
        var selected = obj.selected;
        var legend = obj.name;
        var roundlist=[];
        $.each(selected,function(key,dom){
          if(dom==true){
            roundlist.push(key);
          }
        });
        console.log(roundlist)
        creatAttr(roundlist)

      });
    })
  },
  queryTableData() {
    switch(this.data.pageNum) {
      case 0:
      this.getSystemData();
      this.getChartsData();
      break;
      case 1:
        this.getAccidentData();
        break;
      case 2:
        this.getActiveSafetyData();
        break;
      case 3:
        this.getViolationData();
    }
  },
  initTime() {
    // $('.J-datepickerTime-range').datePicker({
    //   format: 'YYYY-MM-DD HH:mm',
    //   isRange: true
    // });
    //年月日范围
    $('.J-datepicker-range-day').datePicker({
      hasShortcut: true,
      format: 'YYYY-MM-DD',
      isRange: true,
      shortcutOptions: policeinfo.data.DATAPICKERAPI.rangeShortcutOption1
    });
    this.setDatepickerTime();
  },
  setDatepickerTime() {
    var startTime = moment().subtract(7, 'days').format('YYYY-MM-DD');
    var lateDay = moment().subtract(1, 'days').format('YYYY-MM-DD');
    $(".policeInfo_starttime").val(startTime);
    $(".policeInfo_endtime").val(lateDay);
  },
  /**
   * select设置
   */
  selectedValue:function(){
		var self=this;
		var optionArr=["全部","班车客运","旅游包车","危险品运输"];
		self.creatId("#cgstatus",optionArr);
	},
	creatId:function(id,optionArr){
		$(id).html();
		var str="";
		$.each(optionArr,function (i) {
			str+="<option value='"+optionArr[i]+"'>"+optionArr[i]+"</option>"
		});
		$(id).html(str);
		$(id).comboSelect();
	},
  btnEvent() {
    $(".tab_content").on("click","div",function() { // 顶部tab切换
      var index = $(this).index();
      $(".tab_content div").eq(index).addClass("active").siblings().removeClass("active");
      policeinfo.resetQueryData();
      if (index === 0) {
        policeinfo.data.pageNum = 0;
        $(".j-charts-con").show();
        // charts
        policeinfo.getChartsData();
        policeinfo.getSystemData();
      } else {
        $(".j-charts-con").hide();
        if (index === 1) {
          policeinfo.data.pageNum = 1;
          policeinfo.getAccidentData();
        } else if (index === 2) {
          policeinfo.data.pageNum = 2;
          policeinfo.getActiveSafetyData();
        } else if (index === 3) {
          policeinfo.data.pageNum = 3;
          policeinfo.getViolationData();
        }
      }
    });
    $(".search_btn").click(() => {
      policeinfo.queryTableData();
    })
    $(".reset_btn").click(() => {
      policeinfo.resetQueryData();
    })

  }
}

$(function() {
  policeinfo.initcallinfoPage();
})

// window.addEventListener("resize", () => {
//   // this.myChart.resize();
//   charts.pies.resize();
//   charts.LinesArea.resize();
// });
